/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wq.cycling;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.hardware.Camera;
import android.net.Uri;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import activity.MainActivity;
import cn.jpush.android.api.JPushInterface;
import util.MySharePerference;
// ============== fabric start
//import com.crashlytics.android.Crashlytics;
//import io.fabric.sdk.android.Fabric;
// ============== fabric end

public class DemoApplication extends Application {

	public static Context applicationContext;
	private static DemoApplication instance;
	// login user name
	public final String PREF_USERNAME = "username";

	public static List<Activity> activityList = new LinkedList<Activity>();
	public static Context context;
	public static String baseurl = "http://101.37.171.51:8082/";
	public static String token = "";
	public static String deviceid = "";
	public static HashMap<String,Integer> iconmap = new HashMap<>();
	public static HashMap<String,Integer> markermap = new HashMap<>();
	public static HashMap<String,Integer> powermap = new HashMap<>();
	
	/**
	 * nickname for current user, the nickname instead of ID be shown when user receive notification from APNs
	 */
	public static String currentUserNick = "";

	@Override
	public void onCreate() {
		MultiDex.install(this);
		super.onCreate();
        applicationContext = this;
        instance = this;
		context = getApplicationContext();
		DemoHelper.getInstance().init(applicationContext);

		//极光初始化
		JPushInterface.setDebugMode(true);
		JPushInterface.init(this);
		initmarkers();
		initPower();



	}

	public static DemoApplication getInstance() {
		return instance;
	}


	/**
	 * 刷新deviceid
	 *
	 * @param myDeviceid
	 */
	public static void setDeviceid(String myDeviceid) {
		deviceid = myDeviceid;
		MySharePerference.addSharePerference(context,"DEVICEID",myDeviceid);
	}

	public static String getDeviceid() {
		deviceid = MySharePerference.getShardPerferience(context,"DEVICEID","");
		return deviceid;
	}

	/**
	 * 添加电量图标
	 */
	public static void initPower() {
		powermap.put("0", R.mipmap.icon_power0);
		powermap.put("1", R.mipmap.icon_power1);
		powermap.put("2", R.mipmap.icon_power2);
		powermap.put("3", R.mipmap.icon_power3);
		powermap.put("4", R.mipmap.icon_power4);
		powermap.put("5", R.mipmap.icon_power5);
		powermap.put("6", R.mipmap.icon_power6);
		powermap.put("7", R.mipmap.icon_power7);
		powermap.put("8", R.mipmap.icon_power8);
		powermap.put("9", R.mipmap.icon_power9);
		powermap.put("10", R.mipmap.icon_power10);
		powermap.put("11", R.mipmap.icon_power11);
		powermap.put("12", R.mipmap.icon_power12);
		powermap.put("13", R.mipmap.icon_power13);
		powermap.put("14", R.mipmap.icon_power14);
		powermap.put("15", R.mipmap.icon_power15);
	}

	public static int getPower(String key) {
		try {
			if (Integer.valueOf(key) == 0) {
				return powermap.get("0");
			}
			if(Integer.valueOf(key)==100){
				return powermap.get("15");
			}
			if (Integer.valueOf(key) > 0 && Integer.valueOf(key) <= 6) {
				return powermap.get("1");
			}
			if (Integer.valueOf(key) > 6 && Integer.valueOf(key) <= 10) {
				return powermap.get("2");
			}
			if (Integer.valueOf(key) > 10 && Integer.valueOf(key) <= 15) {
				return powermap.get("3");
			}
			if (Integer.valueOf(key) > 15 && Integer.valueOf(key) <= 20) {
				return powermap.get("4");
			}
			if (Integer.valueOf(key) > 20 && Integer.valueOf(key) <= 26) {
				return powermap.get("5");
			}
			if (Integer.valueOf(key) > 26 && Integer.valueOf(key) <= 32) {
				return powermap.get("6");
			}
			if (Integer.valueOf(key) > 32 && Integer.valueOf(key) <= 40) {
				return powermap.get("7");
			}
			if (Integer.valueOf(key) > 40 && Integer.valueOf(key) <= 50) {
				return powermap.get("8");
			}
			if (Integer.valueOf(key) > 50 && Integer.valueOf(key) <= 60) {
				return powermap.get("9");
			}
			if (Integer.valueOf(key) > 60 && Integer.valueOf(key) <= 68) {
				return powermap.get("10");
			}
			if (Integer.valueOf(key) > 68 && Integer.valueOf(key) <= 75) {
				return powermap.get("11");
			}  if (Integer.valueOf(key) > 75 && Integer.valueOf(key) <= 85) {
				return powermap.get("12");
			}
			if (Integer.valueOf(key) > 85 && Integer.valueOf(key) <= 92) {
				return powermap.get("13");
			}
			if (Integer.valueOf(key) > 92 && Integer.valueOf(key) <= 99) {
				return powermap.get("14");
			}


		} catch (Exception e) {
			return powermap.get("0");
		}
		return powermap.get("0");
	}


	/**
	 * 添加marker图标
	 */
	public static void initmarkers(){
		markermap.put("1", R.mipmap.icon_marker1);
		markermap.put("2", R.mipmap.icon_marker2);
		markermap.put("3", R.mipmap.icon_marker3);
	}


	/**
	 *获取marker图标
	 * @param key 图标对应的编号
	 * @return
	 */
	public static int getmarker(String key){
		try {
			return markermap.get(key);
		}catch (Exception e){
			return R.mipmap.icon_marker1;
		}
	}

	/**
	 * 添加Activity到list
	 * @param activity
	 */
	public static void addActivity(Activity activity) {
		activityList.add(activity);
	}

	/**
	 * 遍历clearActivity
	 */
	public static void clearActivity() {
		for (Activity activity : activityList) {
			activity.finish();
		}
		System.exit(0);
	}

	/**
	 * 获取token
	 */
	public static String getToken() {

		if(TextUtils.isEmpty(token)){
			token = MySharePerference.getShardPerferience(context, "TOKEN", "");
		}
		return token;
	}

	public static void setToken(String mToken){
		token = mToken;
		MySharePerference.addSharePerference(context,"TOKEN",token);
	}

	/**
	 *退出登录
	 * @param activity
	 */

	public static void exit2Login(Activity activity) {
		activity.startActivity(new Intent(activity, MainActivity.class));
		DemoApplication.setDeviceid("");
		JPushInterface.stopPush(activity);
		token = "";
		MySharePerference.addSharePerference(context,"TOKEN","");

		EMClient.getInstance().logout(false, new EMCallBack() {

			@Override
			public void onSuccess() {
				Log.d("logut","退出成功");
			}

			@Override
			public void onProgress(int progress, String status) {

			}

			@Override
			public void onError(int code, String error) {
				Log.d("logut","退出失败");
			}
		});

		//MyApplication.clearActivity();
	}

	/**
	 * 退出登录
	 */
	public static void exit() {
		for (Activity activity : activityList) {
			activity.finish();
		}
		System.exit(0);
	}

	/**
	 * 拨打电话
	 * @param phone
	 */
	public static void call(String phone) {
		String uri = phone;
		uri = "tel:" + uri;
		Intent intent = new Intent();
		intent.setAction("android.intent.action.CALL");
		intent.setData(Uri.parse(uri));
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}

	/**
	 * 判断相机权限
	 * @return
	 */
	public static boolean cameraPower() {
		/*
		 * PackageManager pm = context.getPackageManager(); return
		 * (PackageManager.PERMISSION_GRANTED
		 * ==pm.checkPermission("android.permission.CAMERA", "packageName"));
		 */
		boolean canUse = true;
		try {
			Camera mCamera = null;
			try {
				mCamera = Camera.open();
			} catch (Exception e) {
				canUse = false;
			}
			if (canUse) {
				mCamera.release();
				mCamera = null;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		return canUse;
	}

	/**
	 * 获得版本号
	 * @return
	 */
	public static String getVersion() {
		// TODO Auto-generated method stub
		PackageInfo pi;
		try {
			pi = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
			return pi.versionName;
		} catch (PackageManager.NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";

	}

	public static void changeStyle(Activity activity){
		Window window = activity.getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		ViewGroup decorViewGroup = (ViewGroup) window.getDecorView();
		View statusBarView = new View(window.getContext());
		int statusBarHeight = getStatusBarHeight(window.getContext());
		FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, statusBarHeight);
		params.gravity = Gravity.TOP;
		statusBarView.setLayoutParams(params);
		statusBarView.setBackgroundColor(context.getResources().getColor(R.color.iscur));
		decorViewGroup.addView(statusBarView);
	}
	private static int getStatusBarHeight(Context context) {
		int statusBarHeight = 0;
		Resources res = context.getResources();
		int resourceId = res.getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			statusBarHeight = res.getDimensionPixelSize(resourceId);
		}
		return statusBarHeight;
	}


	/**
	 * 设置状态栏图标为深色和魅族特定的文字风格，Flyme4.0以上
	 * 可以用来判断是否为Flyme用户
	 * @param dark 是否把状态栏字体及图标颜色设置为深色
	 * @return  boolean 成功执行返回true
	 *
	 */
	public static boolean FlymeSetStatusBarLightMode(Activity activity, boolean dark) {
		boolean result = false;
		Window window = activity.getWindow();
		if (window != null) {
			try {
				WindowManager.LayoutParams lp = window.getAttributes();
				Field darkFlag = WindowManager.LayoutParams.class
						.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
				Field meizuFlags = WindowManager.LayoutParams.class
						.getDeclaredField("meizuFlags");
				darkFlag.setAccessible(true);
				meizuFlags.setAccessible(true);
				int bit = darkFlag.getInt(null);
				int value = meizuFlags.getInt(lp);
				if (dark) {
					value |= bit;
				} else {
					value &= ~bit;
				}
				meizuFlags.setInt(lp, value);
				window.setAttributes(lp);
				result = true;
			} catch (Exception e) {

			}
		}
		return result;
	}

	/**
	 * 设置状态栏字体图标为深色，需要MIUIV6以上
	 * @param dark 是否把状态栏字体及图标颜色设置为深色
	 * @return  boolean 成功执行返回true
	 *
	 */
	public static boolean MIUISetStatusBarLightMode(Activity activity, boolean dark) {
		boolean result = false;
		Window window = activity.getWindow();
		if (window != null) {
			Class clazz = window.getClass();
			try {
				int darkModeFlag = 0;
				Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
				Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
				darkModeFlag = field.getInt(layoutParams);
				Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
				if(dark){
					extraFlagField.invoke(window,darkModeFlag,darkModeFlag);//状态栏透明且黑色字体
				}else{
					extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
				}
				result=true;
			}catch (Exception e){

			}
		}
		return result;
	}

	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
		MultiDex.install(this);
	}
}
